package com.cloud.pole.weixin.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.util.encoders.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ace.cache.api.CacheAPI;
import com.alibaba.druid.support.json.JSONUtils;
import com.cloud.pole.api.shop.ShopShopsViewApi;
import com.cloud.pole.api.user.BaseUserApi;
import com.cloud.pole.common.constant.CacheConstant;
import com.cloud.pole.common.constant.CommonConstants;
import com.cloud.pole.common.exception.BaseException;
import com.cloud.pole.common.msg.ApiRestResponse;
import com.cloud.pole.common.util.security.AESUtils;
import com.cloud.pole.feign.IShopService;
import com.cloud.pole.feign.IToolService;
import com.cloud.pole.feign.IUserService;
import com.cloud.pole.weixin.biz.WxAppBiz;
import com.cloud.pole.weixin.model.entity.WxApp;
import com.cloud.pole.weixin.model.vo.Code2SessionVo;
import com.cloud.pole.weixin.service.MinProgramService;
import com.cloud.pole.weixin.service.WechatApiService;
import com.cloud.pole.weixin.service.WxUserService;
import com.cloud.pole.weixin.util.wechat.CommonRequest;
import com.cloud.pole.weixin.wechat.CommonService;
import com.cloud.pole.weixin.wechat.domain.AccessToken;
import com.cloud.pole.weixin.wechat.domain.Code2SessionRespMsg;
import com.cloud.pole.weixin.wechat.domain.UserInfo;
import lombok.extern.slf4j.Slf4j;

/*
*2019年5月14日
*cloud-weixin
*author:frank-chen
*/
@Slf4j
@Service
public class MinProgramServiceImpl implements MinProgramService {
	@Autowired
	private WxAppBiz wxAppBiz;
	@Autowired
    private CacheAPI cacheAPI;
	@Autowired
	private WxUserService wxUserService;
	@Autowired
	private IUserService userService;
	@Autowired
	private IShopService shopService;
	@Autowired
	private WechatApiService wechatApiService;
	@Autowired
	private IToolService toolService;
	
	@Override
	public Code2SessionVo code2Session(Integer wxAppId, String jsCode) throws Exception {
		// TODO Auto-generated method stub
		WxApp wxApp = wxAppBiz.selectByPrimaryKey(wxAppId);
		if(wxApp == null || wxApp.getAppStatus().intValue() !=  WxApp.APP_STATUS_OK) {
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "wxAppId错误");
		}
		Code2SessionRespMsg respMsg = CommonService.code2Session(cacheAPI, wxApp.getAppId(), wxApp.getAppSecret(), jsCode);
		if(respMsg == null || StringUtils.isEmpty(respMsg.getOpenid())) {
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "code2Session失败");
		}
		Code2SessionVo msg = new Code2SessionVo();
		msg.setOpenId(respMsg.getOpenid());
		//根据openId登录
		ApiRestResponse<BaseUserApi> userResponse = userService.wxLogin(respMsg.getOpenid());
		if(userResponse != null && userResponse.getStatus() == CommonConstants.STATUS_OK_CODE) {
			msg.setUser(userResponse.getData());
		}
		//最近访问的店铺id
		ApiRestResponse<ShopShopsViewApi> viewApiResponse = shopService.getLastViewShop(respMsg.getOpenid(), null);
		if(viewApiResponse != null && viewApiResponse.getStatus() == CommonConstants.STATUS_OK_CODE) {
			ShopShopsViewApi viewApi = viewApiResponse.getData();
			if(viewApi != null) {
				msg.setLastViewShopId(viewApi.getShopId());
			}
		}
		return msg;
	}

	@Override
	public void addUserInfo(Integer wxAppId, String openId, String nickName, String avatarUrl, Integer gender,
			String country, String province, String city, String language) throws Exception {
		// TODO Auto-generated method stub
		// TODO Auto-generated method stub
		WxApp wxApp = wxAppBiz.selectByPrimaryKey(wxAppId);
		if(wxApp == null || wxApp.getAppStatus().intValue() !=  WxApp.APP_STATUS_OK) {
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "wxAppId错误");
		}
		//保存数据
		UserInfo userInfo = new UserInfo();
		userInfo.setCity(city);
		userInfo.setCountry(country);
		userInfo.setHeadimgurl(avatarUrl);
		userInfo.setLanguage(language);
		userInfo.setNickname(nickName);
		userInfo.setOpenid(openId);
		userInfo.setProvince(province);
		userInfo.setSex(gender);
		wxUserService.modifyWxUser(userInfo, wxApp);
	}

	@Override
	public String decryptData(String openId, String encryptedData, String iv) throws Exception {
		// TODO Auto-generated method stub
		String key =  CacheConstant.SERVICE_WEIXIN_SESSION_KEY + ":"  + openId;
		String sessionKey = cacheAPI.get(key);
		if(StringUtils.isEmpty(sessionKey)) {
			throw new BaseException(CommonConstants.WX_CODE_ERROR_EXPIRE_STATUS, CommonConstants.WX_CODE_ERROR_EXPIRE_INFO);
		}
		byte[] byteData = AESUtils.decrypt(Base64.decode(encryptedData), Base64.decode(sessionKey), Base64.decode(iv));
		if(byteData == null) {
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "解密失败");
		}
		String data = new String(byteData, "UTF-8");
		return data;
	}

	@Override
	public String getWxQrCodeUnLimit(Integer wxAppId, String scene, String page) throws Exception {
		// TODO Auto-generated method stub
		WxApp wxApp = wxAppBiz.selectByPrimaryKey(wxAppId);
		if(wxApp == null || wxApp.getAppStatus().intValue() !=  WxApp.APP_STATUS_OK) {
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "wxAppId错误");
		}
		AccessToken accessToken = wechatApiService.getAccessToken(wxApp);
		if(accessToken == null || StringUtils.isEmpty(accessToken.getAccess_token())) {
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "获取accessToken失败");
		}
		String strUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken.getAccess_token();
		log.info(strUrl);
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("scene", scene);
//		paramMap.put("page", page);
		String strJson = JSONUtils.toJSONString(paramMap);
		byte[] byteResp = CommonRequest.doPostJsonToBytes(strUrl, strJson);
		//调用图片上传接口
		ApiRestResponse<String> response = toolService.uploadImage(byteResp, "shopQRcode", "jpg");
		if(response == null || response.getStatus() != CommonConstants.STATUS_OK_CODE) {
			throw new BaseException(CommonConstants.STATUS_ERROR_CODE, "保存图片失败");
		}
		return response.getData();
	}
}
